import UIKit
import SnapKit
import Kingfisher

class ImageRenderer {
    private let theme: MarkdownTheme
    private let containerWidth: CGFloat
    private let imageBaseURL: URL?
    private weak var delegate: MarkdownViewDelegate?
    private let nodeLogger = MarkdownLogger.shared
    
    private var imageURLs: [Int: URL] = [:]
    private var nextImageTag = 1
    
    init(theme: MarkdownTheme, containerWidth: CGFloat, imageBaseURL: URL?, delegate: MarkdownViewDelegate?) {
        self.theme = theme
        self.containerWidth = max(0, containerWidth)
        self.imageBaseURL = imageBaseURL
        self.delegate = delegate
        
        nodeLogger.debug("""
        ImageRenderer initialized:
        - Container width: \(containerWidth)
        - Image base URL: \(String(describing: imageBaseURL))
        - Theme: \(String(describing: theme))
        - Delegate: \(String(describing: delegate))
        """)
    }
    
    func renderImage(from urlString: String?, title: String? = nil) -> UIView {
        nodeLogger.debug("Starting image rendering: \(urlString ?? "nil"), title: \(title ?? "nil")")
        
        // 创建容器视图
        let containerView = UIView()
        containerView.backgroundColor = theme.image.backgroundColor
        
        // 创建加载指示器容器视图
        let loadingContainer = UIView()
        loadingContainer.backgroundColor = theme.image.backgroundColor.withAlphaComponent(0.7)
        loadingContainer.layer.cornerRadius = theme.image.cornerRadius
        
        // 创建图片视图
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = theme.image.cornerRadius
        imageView.backgroundColor = theme.image.backgroundColor
        
        // 创建标题标签
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        titleLabel.font = theme.image.titleFont
        titleLabel.textColor = theme.image.titleColor
        titleLabel.text = title
        titleLabel.isHidden = title == nil
        
        // 添加加载指示器
        let activityIndicator = UIActivityIndicatorView(style: theme.image.loadingIndicatorStyle)
        activityIndicator.hidesWhenStopped = true
        activityIndicator.startAnimating()
        
        // 创建加载文本标签
        let loadingLabel = UILabel()
        loadingLabel.text = "Loading..."
        loadingLabel.font = .systemFont(ofSize: 12)
        loadingLabel.textColor = .secondaryLabel
        loadingLabel.textAlignment = .center
        
        // 设置占位图
        let placeholderImage = UIImage(systemName: "photo")?
            .withTintColor(theme.image.placeholderColor, renderingMode: .alwaysOriginal)
        imageView.image = placeholderImage
        
        // 添加子视图
        containerView.addSubview(imageView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(loadingContainer)
        loadingContainer.addSubview(activityIndicator)
        loadingContainer.addSubview(loadingLabel)
        
        // 设置约束
        imageView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.centerX.equalToSuperview()
            make.width.equalTo(theme.image.maxWidth)
            make.height.equalTo(200) // 初始高度，加载后会更新
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(imageView.snp.bottom).offset(8)
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(titleLabel.isHidden ? 0 : -8)
        }
        
        loadingContainer.snp.makeConstraints { make in
            make.edges.equalTo(imageView)
        }
        
        activityIndicator.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-10)
        }
        
        loadingLabel.snp.makeConstraints { make in
            make.top.equalTo(activityIndicator.snp.bottom).offset(8)
            make.centerX.equalToSuperview()
        }
        
        // 设置容器视图的初始宽度
        containerView.snp.makeConstraints { make in
            make.width.equalTo(theme.image.maxWidth)
        }
        
        // 处理图片 URL
        if let urlString = urlString {
            let finalURL: URL?
            
            if let url = URL(string: urlString) {
                if url.scheme == nil, let baseURL = imageBaseURL {
                    // 相对路径，使用 baseURL
                    finalURL = baseURL.appendingPathComponent(urlString)
                } else {
                    // 完整 URL
                    finalURL = url
                }
            } else if let baseURL = imageBaseURL {
                // 尝试作为相对路径处理
                finalURL = baseURL.appendingPathComponent(urlString)
            } else {
                finalURL = nil
            }
            
            if let finalURL = finalURL {
                nodeLogger.debug("Loading image from URL: \(finalURL)")
                
                // 使用 Kingfisher 加载图片
                imageView.kf.setImage(
                    with: finalURL,
                    placeholder: placeholderImage,
                    options: [
                        .transition(.fade(0.3)),
                        .processor(DownsamplingImageProcessor(size: CGSize(width: theme.image.maxWidth, height: 4000))),
                        .scaleFactor(UIScreen.main.scale),
                        .cacheOriginalImage
                    ]
                ) { [weak self, weak imageView, weak containerView, weak loadingContainer] result in
                    // 隐藏加载指示器
                    UIView.animate(withDuration: 0.3) {
                        loadingContainer?.alpha = 0
                    } completion: { _ in
                        loadingContainer?.removeFromSuperview()
                    }
                    
                    switch result {
                    case .success(let value):
                        self?.nodeLogger.debug("Image loaded successfully: \(value.image.size)")
                        
                        // 计算适当的显示尺寸
                        let maxWidth = min(self?.theme.image.maxWidth ?? 0, self?.containerWidth ?? 0)
                        var targetSize = value.image.size
                        
                        if targetSize.width > maxWidth {
                            let ratio = maxWidth / targetSize.width
                            targetSize = CGSize(width: maxWidth, height: targetSize.height * ratio)
                        }
                        
                        // 设置图片
                        imageView?.image = value.image
                        
                        // 更新图片视图约束
                        imageView?.snp.remakeConstraints { make in
                            make.top.equalToSuperview()
                            make.centerX.equalToSuperview()
                            make.width.equalTo(targetSize.width)
                            make.height.equalTo(targetSize.height)
                        }
                        
                        // 更新标题标签约束
                        titleLabel.snp.remakeConstraints { make in
                            make.top.equalTo(imageView!.snp.bottom).offset(8)
                            make.leading.trailing.equalToSuperview().inset(16)
                            make.bottom.equalToSuperview().offset(titleLabel.isHidden ? 0 : -8)
                        }
                        
                        // 更新容器视图约束
                        containerView?.snp.makeConstraints { make in
                            make.width.equalTo(targetSize.width)
                        }
                        
                        // 强制布局更新
                        containerView?.setNeedsLayout()
                        containerView?.layoutIfNeeded()
                        
                        // 通知父视图需要更新布局
                        containerView?.superview?.setNeedsLayout()
                        containerView?.superview?.layoutIfNeeded()
                        
                        // 添加点击手势
                        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self?.handleImageTap(_:)))
                        containerView?.addGestureRecognizer(tapGesture)
                        containerView?.isUserInteractionEnabled = true
                        
                        // 存储图片 URL 用于点击处理
                        if let tag = self?.storeImageURL(finalURL) {
                            containerView?.tag = tag
                        }
                        
                        // 通知代理
                        self?.delegate?.markdownView(didLoadImage: value.image, from: finalURL)
                        
                    case .failure(let error):
                        self?.nodeLogger.error("Failed to load image: \(error.localizedDescription)")
                        
                        // 显示错误占位图
                        imageView?.image = UIImage(systemName: "exclamationmark.triangle")?
                            .withTintColor(self?.theme.image.placeholderColor ?? .systemRed, renderingMode: .alwaysOriginal)
                        
                        // 更新图片视图约束到最小高度
                        imageView?.snp.updateConstraints { make in
                            make.height.equalTo(100)
                        }
                        
                        // 通知代理
                        self?.delegate?.markdownView(didFailToLoadImage: finalURL, error: error)
                    }
                }
            } else {
                nodeLogger.warning("Could not create valid URL from string: \(urlString)")
                loadingContainer.removeFromSuperview()
            }
        } else {
            nodeLogger.warning("No URL string provided")
            loadingContainer.removeFromSuperview()
        }
        
        return containerView
    }
    
    @objc private func handleImageTap(_ gesture: UITapGestureRecognizer) {
        guard let view = gesture.view,
              let url = imageURLs[view.tag] else {
            nodeLogger.warning("Invalid image tap: no URL found for tag \(gesture.view?.tag ?? -1)")
            return
        }
        
        nodeLogger.debug("Image tapped: \(url)")
        delegate?.markdownView(didTapImage: url)
    }
    
    private func storeImageURL(_ url: URL) -> Int {
        let tag = nextImageTag
        imageURLs[tag] = url
        nextImageTag += 1
        nodeLogger.debug("Stored image URL: \(url) with tag: \(tag)")
        return tag
    }
} 
